import 'package:magma/heartbeat/helpers/magma_constant.dart';
import 'package:stacked/stacked.dart';
import '../heartbeat/blueprint/club_model.dart';

/// 俱乐部管理者
class ClubManager extends BaseViewModel {
  // 俱乐部列表（模拟数据库）
  final List<ClubModel> _clubs = [];

  // 俱乐部群聊消息列表
  final List<ClubMessageModel> _messages = [];

  /// 获取所有俱乐部
  List<ClubModel> get clubs => List.from(_clubs);

  /// 获取所有消息
  List<ClubMessageModel> get messages => List.from(_messages);

  /// 初始化默认俱乐部数据
  void initializeDefaultClubs() {
    _clubs.clear();
    _clubs.addAll(_getDefaultClubs());
    _initializeDefaultMessages();
  }

  /// 获取默认俱乐部数据
  List<ClubModel> _getDefaultClubs() {
    return [
      ClubModel(
        id: '1',
        name: 'Thunder Runners',
        description:
            'Join us to sweat, challenge yourself and break your limits!',
        image: MagmaConstant.group1,
        creatorId: '1',
        maxMembers: 50,
        currentMembers: 10,
        createdAt: DateTime.now().subtract(const Duration(days: 15)),
        memberIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      ),
      ClubModel(
        id: '2',
        name: 'Marathon Warriors',
        description:
            'Share the love of long-distance running with fellow runners!',
        image: MagmaConstant.group2,
        creatorId: '2',
        maxMembers: 30,
        currentMembers: 9,
        createdAt: DateTime.now().subtract(const Duration(days: 12)),
        memberIds: ['2', '3', '4', '5', '6', '7', '8', '9', '10'],
      ),
      ClubModel(
        id: '3',
        name: 'Speed Demons',
        description:
            'Let\'s run towards more wonderful things in life together!',
        image: MagmaConstant.group3,
        creatorId: '3',
        maxMembers: 25,
        currentMembers: 8,
        createdAt: DateTime.now().subtract(const Duration(days: 8)),
        memberIds: ['3', '4', '5', '6', '7', '8', '9', '10'],
      ),
      ClubModel(
        id: '4',
        name: 'Track Legends',
        description: 'There is passion on the track and friends in the club!',
        image: MagmaConstant.group4,
        creatorId: '4',
        maxMembers: 40,
        currentMembers: 7,
        createdAt: DateTime.now().subtract(const Duration(days: 20)),
        memberIds: ['4', '5', '6', '7', '8', '9', '10'],
      ),
    ];
  }

  /// 初始化默认消息数据
  void _initializeDefaultMessages() {
    _messages.clear();
    _messages.addAll(_getDefaultMessages());
  }

  /// 获取默认消息数据
  List<ClubMessageModel> _getDefaultMessages() {
    return [
      // Thunder Runners 俱乐部消息
      ClubMessageModel(
        id: '1',
        clubId: '1',
        userId: '1',
        content:
            'Welcome to Thunder Runners! Let\'s push our limits together! 💪',
        createdAt: DateTime.now().subtract(const Duration(days: 15, hours: 2)),
      ),
      ClubMessageModel(
        id: '2',
        clubId: '1',
        userId: '2',
        content:
            'Just completed my first 10K with the club! Amazing experience!',
        createdAt: DateTime.now().subtract(const Duration(days: 14, hours: 5)),
      ),
      ClubMessageModel(
        id: '3',
        clubId: '1',
        userId: '3',
        content: 'Anyone up for a morning run tomorrow? 6 AM at Central Park!',
        createdAt: DateTime.now().subtract(const Duration(days: 13, hours: 8)),
      ),
      ClubMessageModel(
        id: '4',
        clubId: '1',
        userId: '4',
        content: 'Count me in! I\'ll be there with my new running shoes!',
        createdAt: DateTime.now().subtract(const Duration(days: 13, hours: 7)),
      ),
      ClubMessageModel(
        id: '5',
        clubId: '1',
        userId: '5',
        content: 'Great run this morning! The energy was incredible!',
        createdAt: DateTime.now().subtract(const Duration(days: 12, hours: 2)),
      ),
      ClubMessageModel(
        id: '6',
        clubId: '1',
        userId: '6',
        content:
            'Training for my first marathon. Any tips from experienced runners?',
        createdAt: DateTime.now().subtract(const Duration(days: 11, hours: 6)),
      ),
      ClubMessageModel(
        id: '7',
        clubId: '1',
        userId: '7',
        content:
            'Consistency is key! Start with shorter distances and gradually increase.',
        createdAt: DateTime.now().subtract(const Duration(days: 11, hours: 5)),
      ),
      ClubMessageModel(
        id: '8',
        clubId: '1',
        userId: '8',
        content:
            'Don\'t forget to rest and fuel properly! Your body needs recovery time.',
        createdAt: DateTime.now().subtract(const Duration(days: 11, hours: 4)),
      ),

      // Marathon Warriors 俱乐部消息
      ClubMessageModel(
        id: '9',
        clubId: '2',
        userId: '2',
        content:
            'Welcome to Marathon Warriors! Let\'s conquer those long distances! 🏃‍♂️',
        createdAt: DateTime.now().subtract(const Duration(days: 12, hours: 3)),
      ),
      ClubMessageModel(
        id: '10',
        clubId: '2',
        userId: '3',
        content: 'Long distance running is a mental game as much as physical!',
        createdAt: DateTime.now().subtract(const Duration(days: 11, hours: 7)),
      ),
      ClubMessageModel(
        id: '11',
        clubId: '2',
        userId: '4',
        content:
            'The wall at mile 20 is real! But crossing the finish line makes it all worth it!',
        createdAt: DateTime.now().subtract(const Duration(days: 10, hours: 4)),
      ),
      ClubMessageModel(
        id: '12',
        clubId: '2',
        userId: '5',
        content: 'Anyone else running the Boston Marathon next month?',
        createdAt: DateTime.now().subtract(const Duration(days: 9, hours: 8)),
      ),
      ClubMessageModel(
        id: '13',
        clubId: '2',
        userId: '6',
        content: 'I am! First time running Boston. Any advice for the course?',
        createdAt: DateTime.now().subtract(const Duration(days: 9, hours: 7)),
      ),
      ClubMessageModel(
        id: '14',
        clubId: '2',
        userId: '7',
        content:
            'Heartbreak Hill is tough but manageable if you pace yourself early!',
        createdAt: DateTime.now().subtract(const Duration(days: 9, hours: 6)),
      ),
      ClubMessageModel(
        id: '15',
        clubId: '2',
        userId: '8',
        content:
            'The crowd support in Boston is incredible! It will carry you through!',
        createdAt: DateTime.now().subtract(const Duration(days: 9, hours: 5)),
      ),
      ClubMessageModel(
        id: '16',
        clubId: '2',
        userId: '9',
        content: 'Good luck everyone! Remember to enjoy the journey!',
        createdAt: DateTime.now().subtract(const Duration(days: 8, hours: 3)),
      ),

      // Speed Demons 俱乐部消息
      ClubMessageModel(
        id: '17',
        clubId: '3',
        userId: '3',
        content:
            'Welcome to Speed Demons! Let\'s chase those personal bests! ⚡',
        createdAt: DateTime.now().subtract(const Duration(days: 8, hours: 4)),
      ),
      ClubMessageModel(
        id: '18',
        clubId: '3',
        userId: '4',
        content:
            'Speed work is my favorite! Nothing beats the feeling of flying!',
        createdAt: DateTime.now().subtract(const Duration(days: 7, hours: 6)),
      ),
      ClubMessageModel(
        id: '19',
        clubId: '3',
        userId: '5',
        content: 'Track workouts are brutal but so rewarding!',
        createdAt: DateTime.now().subtract(const Duration(days: 6, hours: 8)),
      ),
      ClubMessageModel(
        id: '20',
        clubId: '3',
        userId: '6',
        content: 'Anyone want to do some interval training this weekend?',
        createdAt: DateTime.now().subtract(const Duration(days: 5, hours: 7)),
      ),
      ClubMessageModel(
        id: '21',
        clubId: '3',
        userId: '7',
        content: 'I\'m in! What time and where?',
        createdAt: DateTime.now().subtract(const Duration(days: 5, hours: 6)),
      ),
      ClubMessageModel(
        id: '22',
        clubId: '3',
        userId: '8',
        content: 'Let\'s meet at the track at 7 AM! Bring your stopwatch!',
        createdAt: DateTime.now().subtract(const Duration(days: 5, hours: 5)),
      ),
      ClubMessageModel(
        id: '23',
        clubId: '3',
        userId: '9',
        content: 'Perfect! See you all there!',
        createdAt: DateTime.now().subtract(const Duration(days: 5, hours: 4)),
      ),
      ClubMessageModel(
        id: '24',
        clubId: '3',
        userId: '10',
        content: 'Great session today! My 5K time improved by 30 seconds!',
        createdAt: DateTime.now().subtract(const Duration(days: 4, hours: 2)),
      ),

      // Track Legends 俱乐部消息
      ClubMessageModel(
        id: '25',
        clubId: '4',
        userId: '4',
        content: 'Welcome to Track Legends! Where passion meets friendship! 🏆',
        createdAt: DateTime.now().subtract(const Duration(days: 20, hours: 5)),
      ),
      ClubMessageModel(
        id: '26',
        clubId: '4',
        userId: '5',
        content: 'This club has been my second family for years!',
        createdAt: DateTime.now().subtract(const Duration(days: 19, hours: 8)),
      ),
      ClubMessageModel(
        id: '27',
        clubId: '4',
        userId: '6',
        content:
            'The support here is incredible! Everyone pushes each other to be better!',
        createdAt: DateTime.now().subtract(const Duration(days: 18, hours: 6)),
      ),
      ClubMessageModel(
        id: '28',
        clubId: '4',
        userId: '7',
        content:
            'Just won my age group in the local 10K! Thanks to all the training tips!',
        createdAt: DateTime.now().subtract(const Duration(days: 17, hours: 4)),
      ),
      ClubMessageModel(
        id: '29',
        clubId: '4',
        userId: '8',
        content: 'Congratulations! That\'s amazing! 🎉',
        createdAt: DateTime.now().subtract(const Duration(days: 17, hours: 3)),
      ),
      ClubMessageModel(
        id: '30',
        clubId: '4',
        userId: '9',
        content: 'Well done! Your hard work paid off!',
        createdAt: DateTime.now().subtract(const Duration(days: 17, hours: 2)),
      ),
      ClubMessageModel(
        id: '31',
        clubId: '4',
        userId: '10',
        content: 'Anyone up for a long run this Sunday? Planning 20 miles!',
        createdAt: DateTime.now().subtract(const Duration(days: 16, hours: 7)),
      ),
      ClubMessageModel(
        id: '32',
        clubId: '4',
        userId: '1',
        content: 'I\'m training for an ultra-marathon! Count me in!',
        createdAt: DateTime.now().subtract(const Duration(days: 16, hours: 6)),
      ),
      ClubMessageModel(
        id: '33',
        clubId: '4',
        userId: '2',
        content: '20 miles sounds perfect! What\'s the route?',
        createdAt: DateTime.now().subtract(const Duration(days: 16, hours: 5)),
      ),
      ClubMessageModel(
        id: '34',
        clubId: '4',
        userId: '3',
        content:
            'Let\'s do the river trail! Beautiful scenery and mostly flat!',
        createdAt: DateTime.now().subtract(const Duration(days: 16, hours: 4)),
      ),
      ClubMessageModel(
        id: '35',
        clubId: '4',
        userId: '4',
        content: 'Perfect! See you all at 6 AM at the trailhead!',
        createdAt: DateTime.now().subtract(const Duration(days: 16, hours: 3)),
      ),
    ];
  }

  /// 创建俱乐部
  Future<bool> establishClub({
    required String name,
    required String description,
    required String image,
    required String creatorId,
    required int maxMembers,
  }) async {
    setBusy(true);
    try {
      if (name.trim().isEmpty) {
        setError('Club name cannot be empty');
        return false;
      }

      if (description.trim().isEmpty) {
        setError('Club description cannot be empty');
        return false;
      }

      if (maxMembers < 2) {
        setError('Club must allow at least 2 members');
        return false;
      }

      // 创建俱乐部记录
      final club = ClubModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        name: name.trim(),
        description: description.trim(),
        image: image,
        creatorId: creatorId,
        maxMembers: maxMembers,
        currentMembers: 1,
        createdAt: DateTime.now(),
        memberIds: [creatorId],
      );

      _clubs.insert(0, club); // 插入到列表开头

      // 添加欢迎消息
      final welcomeMessage = ClubMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString() + '_welcome',
        clubId: club.id,
        userId: creatorId,
        content:
            'Welcome to $name! Let\'s start this amazing journey together! 🎉',
        createdAt: DateTime.now(),
      );
      _messages.add(welcomeMessage);

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 加入俱乐部
  Future<bool> enrollInClub({
    required String clubId,
    required String userId,
  }) async {
    setBusy(true);
    try {
      final clubIndex = _clubs.indexWhere((club) => club.id == clubId);
      if (clubIndex == -1) {
        setError('Club not found');
        return false;
      }

      final club = _clubs[clubIndex];

      // 检查是否已经是成员
      if (club.memberIds.contains(userId)) {
        setError('You are already a member of this club');
        return false;
      }

      // 检查是否已满员
      if (club.currentMembers >= club.maxMembers) {
        setError('Club is full');
        return false;
      }

      // 更新俱乐部成员
      final updatedMemberIds = List<String>.from(club.memberIds)..add(userId);
      _clubs[clubIndex] = club.copyWith(
        currentMembers: club.currentMembers + 1,
        memberIds: updatedMemberIds,
      );

      // 添加加入消息
      final joinMessage = ClubMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString() + '_join',
        clubId: clubId,
        userId: userId,
        content:
            'Just joined the club! Excited to be part of this amazing community! 🏃‍♂️',
        createdAt: DateTime.now(),
      );
      _messages.add(joinMessage);

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 退出俱乐部
  Future<bool> withdrawFromClub({
    required String clubId,
    required String userId,
  }) async {
    setBusy(true);
    try {
      final clubIndex = _clubs.indexWhere((club) => club.id == clubId);
      if (clubIndex == -1) {
        setError('Club not found');
        return false;
      }

      final club = _clubs[clubIndex];

      // 检查是否是成员
      if (!club.memberIds.contains(userId)) {
        setError('You are not a member of this club');
        return false;
      }

      // 检查是否是创建者
      if (club.creatorId == userId) {
        setError('Club creator cannot leave the club');
        return false;
      }

      // 更新俱乐部成员
      final updatedMemberIds = List<String>.from(club.memberIds)
        ..remove(userId);
      _clubs[clubIndex] = club.copyWith(
        currentMembers: club.currentMembers - 1,
        memberIds: updatedMemberIds,
      );

      // 添加退出消息
      final leaveMessage = ClubMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString() + '_leave',
        clubId: clubId,
        userId: userId,
        content:
            'Thanks for the great times! Leaving the club but keeping the memories! 👋',
        createdAt: DateTime.now(),
      );
      _messages.add(leaveMessage);

      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 发送群聊消息
  Future<bool> dispatchMessage({
    required String clubId,
    required String userId,
    required String content,
  }) async {
    setBusy(true);
    try {
      if (content.trim().isEmpty) {
        setError('Message content cannot be empty');
        return false;
      }

      // 验证用户是俱乐部成员
      final club = _clubs.firstWhere(
        (c) => c.id == clubId,
        orElse: () => throw Exception('Club not found'),
      );

      if (!club.memberIds.contains(userId)) {
        setError('You must be a member to send messages');
        return false;
      }

      // 创建消息记录
      final message = ClubMessageModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        clubId: clubId,
        userId: userId,
        content: content.trim(),
        createdAt: DateTime.now(),
      );

      _messages.add(message);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 获取俱乐部的所有消息
  List<ClubMessageModel> retrieveClubMessages(String clubId) {
    return _messages.where((message) => message.clubId == clubId).toList()
      ..sort((a, b) => a.createdAt.compareTo(b.createdAt));
  }

  /// 清空俱乐部的所有消息
  Future<bool> clearClubMessages(String clubId) async {
    setBusy(true);
    try {
      _messages.removeWhere((message) => message.clubId == clubId);
      notifyListeners();
      return true;
    } catch (e) {
      setError(e.toString());
      return false;
    } finally {
      setBusy(false);
    }
  }

  /// 获取用户加入的俱乐部
  List<ClubModel> fetchUserClubs(String userId) {
    return _clubs.where((club) => club.memberIds.contains(userId)).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  /// 根据ID获取俱乐部
  ClubModel? locateClub(String clubId) {
    try {
      return _clubs.firstWhere((club) => club.id == clubId);
    } catch (e) {
      return null;
    }
  }

  /// 检查用户是否是俱乐部成员
  bool isUserMember(String clubId, String userId) {
    final club = locateClub(clubId);
    return club?.memberIds.contains(userId) ?? false;
  }

  /// 搜索俱乐部
  List<ClubModel> exploreClubs(String keyword) {
    if (keyword.isEmpty) return clubs;

    return _clubs.where((club) {
      return club.name.toLowerCase().contains(keyword.toLowerCase()) ||
          club.description.toLowerCase().contains(keyword.toLowerCase());
    }).toList();
  }
}
